Importing Packages & Set Up Data LayoutΒΆ

Preprocessing Information for the Given Data.ΒΆ

A high-pass filter with a 30 Hz cut-off frequency and a power line notch filter (50 Hz) were used. All recordings are artifact-free EEG segments of 60 seconds duration. At the stage of data preprocessing, the Independent Component Analysis (ICA) was used to eliminate the artifacts (eyes, muscle, and cardiac overlapping of the cardiac pulsation). The arithmetic task was the serial subtraction of two numbers. Each trial started with the communication orally 4-digit (minuend) and 2-digit (subtrahend) numbers (e.g. 3141 and 42).

InΒ [1]:
# Let's load some packages we need (pip install mne)
import mne
import mne.viz
from mne.datasets import eegbci
from mne.io import concatenate_raws, read_raw_edf
from mne.channels import make_standard_montage
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
# ! pip install mne

# Read raw data files where each file contains a run
files = ['../datasets/HW2Datasets/Subject06_1.edf', '../datasets/HW2Datasets/Subject06_2.edf', '../datasets/HW2Datasets/Subject07_1.edf', '../datasets/HW2Datasets/Subject07_2.edf']

# Read the raw EDF files into an array
raws = [read_raw_edf(f, preload=True) for f in files]

# Loop through the array and make the following changes to the raw files
for raw in raws:

    # Rename the raw channels
    raw.rename_channels({'EEG F3':'F3', 'EEG F4':'F4',
                            'EEG Fp1':'Fp1', 'EEG Fp2':'Fp2', 'EEG F7':'F7', 'EEG F8':'F8',
                            'EEG T3':'T3', 'EEG T4':'T4', 'EEG C3':'C3', 'EEG C4':'C4',
                            'EEG T5':'T5', 'EEG T6':'T6', 'EEG P3':'P3', 'EEG P4':'P4',
                            'EEG O1':'O1', 'EEG O2':'O2', 'EEG Fz':'Fz', 'EEG Cz':'Cz',
                            'EEG Pz':'Pz', 'EEG A2-A1':'A2', 'ECG ECG':'ECG'})


    # Set channel types
    raw.set_channel_types({'ECG':'ecg'})

    # Define the channel locations
    raw.set_montage(mne.channels.make_standard_montage('standard_1020'))

    # Print Raw Channel Names for double checking
    print(raw.ch_names)

# Rename the raws with more insightfull names
subject6_background = raws[0] # Subject 6 background raw
subject6_task = raws[1] # Subject 6 task raw
subject7_background = raws[2] # Subject 7 background raw
subject7_task = raws[3] # Subject 7 task raw
Extracting EDF parameters from /home/joshua/Desktop/MainFolder/OuClasses/2024 Fall/Neural-Data-Science/datasets/HW2Datasets/Subject06_1.edf...
EDF file detected
Setting channel info structure...
Creating raw.info structure...
Reading 0 ... 90999  =      0.000 ...   181.998 secs...
EDF file detected
Setting channel info structure...
Creating raw.info structure...
Reading 0 ... 90999  =      0.000 ...   181.998 secs...
Extracting EDF parameters from /home/joshua/Desktop/MainFolder/OuClasses/2024 Fall/Neural-Data-Science/datasets/HW2Datasets/Subject06_2.edf...
EDF file detected
Setting channel info structure...
Creating raw.info structure...
Reading 0 ... 30999  =      0.000 ...    61.998 secs...
Extracting EDF parameters from /home/joshua/Desktop/MainFolder/OuClasses/2024 Fall/Neural-Data-Science/datasets/HW2Datasets/Subject07_1.edf...
EDF file detected
Setting channel info structure...
Creating raw.info structure...
Reading 0 ... 90999  =      0.000 ...   181.998 secs...
Extracting EDF parameters from /home/joshua/Desktop/MainFolder/OuClasses/2024 Fall/Neural-Data-Science/datasets/HW2Datasets/Subject07_2.edf...
EDF file detected
Setting channel info structure...
Creating raw.info structure...
Reading 0 ... 30999  =      0.000 ...    61.998 secs...
['Fp1', 'Fp2', 'F3', 'F4', 'F7', 'F8', 'T3', 'T4', 'C3', 'C4', 'T5', 'T6', 'P3', 'P4', 'O1', 'O2', 'Fz', 'Cz', 'Pz', 'A2', 'ECG']
['Fp1', 'Fp2', 'F3', 'F4', 'F7', 'F8', 'T3', 'T4', 'C3', 'C4', 'T5', 'T6', 'P3', 'P4', 'O1', 'O2', 'Fz', 'Cz', 'Pz', 'A2', 'ECG']
['Fp1', 'Fp2', 'F3', 'F4', 'F7', 'F8', 'T3', 'T4', 'C3', 'C4', 'T5', 'T6', 'P3', 'P4', 'O1', 'O2', 'Fz', 'Cz', 'Pz', 'A2', 'ECG']
['Fp1', 'Fp2', 'F3', 'F4', 'F7', 'F8', 'T3', 'T4', 'C3', 'C4', 'T5', 'T6', 'P3', 'P4', 'O1', 'O2', 'Fz', 'Cz', 'Pz', 'A2', 'ECG']

Q1)ΒΆ

Plot the power spectral density for the two conditions (background and task). Discuss the main difference between the two groups.ΒΆ

For this task, I have ploted 4 power spectral density plots for each of the subjects and states along with a custom mean spectral density plot to better see some overall occuring trends.

InΒ [2]:
# Plot Subject 6 Background between 1hz and 50hz
subject6_background.plot_psd(fmin=1, fmax=50)
plt.title('Subject 6 Background') # Set Title for easier interpretation
plt.show() # Show plot
NOTE: plot_psd() is a legacy function. New code should use .compute_psd().plot().
Effective window size : 4.096 (s)
Plotting power spectral density (dB=True).
/home/joshua/.local/lib/python3.10/site-packages/mne/viz/utils.py:158: UserWarning: FigureCanvasAgg is non-interactive, and thus cannot be shown
  (fig or plt).show(**kwargs)
No description has been provided for this image

The plot above (subject 6 background state) is one that has a mini ramp up in power at frequency 12hz or so. Another thing to mention is that most of the channels near the frontal lobe (left dominant) are occupied from frequencies 1hz to around 8hz and then it flips to a primarly occipital lobe (right dominant) occupied from frequencies 8hz to around 14hz. After that there is no noticeably active area all relatively equal from 14hz to the end (50hz here) besides a purple channel (occipital lobe) becomes more powerful compared to the rest. Also last thing to mention here, the orange channel is way weaker than the other signals and could be because it's on the side of the head where it's harder to read the signal.

InΒ [3]:
# Plot Subject 6 Task between 1hz and 50hz
subject6_task.plot_psd(fmin=1, fmax=50)
plt.title('Subject 6 Task') # Set Title for easier interpretation
plt.show() # Show plot
NOTE: plot_psd() is a legacy function. New code should use .compute_psd().plot().
Effective window size : 4.096 (s)
Plotting power spectral density (dB=True).
/home/joshua/.local/lib/python3.10/site-packages/mne/viz/utils.py:158: UserWarning: FigureCanvasAgg is non-interactive, and thus cannot be shown
  (fig or plt).show(**kwargs)
No description has been provided for this image

The plot above (subject 6 test state) also has a mini ramp up near 12hz, however the power of that ramp up is less in this plot vs the previous one (10dB to 6dB) potentially indecating a lower usage of the occipital lobe. The Frontal lobe (left dominant) from before grows in it's relative power from 1hz to 10hz over the other channels and the other channels (purple, red, dark blue) even condense down, becoming more dense under the the Frontal lobe lines (green & cyan colors). The dominance of the Frontal lobe continues right after the mini ramp up after around 12hz to 22hz or so, but less so in comparison to the 1hz to 10hz area. Another very important thing to mention is the fact that the power of higher frequencies is greater on average in the task plot than on the background plot, showing more energy being needed in the brain to solve the task. We can see this by looking at 30hz (Task: -5dB to -10dB vs Background: -8dB to -11dB) & 40hz (Task: -8B to -12dB vs Background: -12 to -18db). Amplitude also seems to be higher on the task vs the background state.

This tells us that the task given (solving math problems) activates more areas in the frontal lobe in comparison to other areas of the brain and more importantly, require more energy in all areas of the brain in general. This makes sense due to studies showing us that the frontal lobe is critial for complex problem solving and that it takes energy to make a computation.

InΒ [4]:
# Plot Subject 7 Background between 1hz and 50hz
subject7_background.plot_psd(fmin=1, fmax=50)
plt.title('Subject 7 Background') # Set Title for easier interpretation
plt.show() # Show plot
NOTE: plot_psd() is a legacy function. New code should use .compute_psd().plot().
Effective window size : 4.096 (s)
Plotting power spectral density (dB=True).
/home/joshua/.local/lib/python3.10/site-packages/mne/viz/utils.py:158: UserWarning: FigureCanvasAgg is non-interactive, and thus cannot be shown
  (fig or plt).show(**kwargs)
No description has been provided for this image

The plot above (subject 7 background state) is similar to subject 6 background state outside of the fact that the Occipital lobe (right dominant) is the most powerful section from 1hz to 25hz or so and that the small hump happens at around 7hz to 8hz at 20dB. Also from 26hz+, the dominant channels seem to be from the Frontal lobe (lime & yellow).

InΒ [5]:
# Plot Subject 7 Task between 1hz and 50hz
subject7_task.plot_psd(fmin=1, fmax=50)
plt.title('Subject 7 Task') # Set Title for easier interpretation
plt.show() # Show plot
NOTE: plot_psd() is a legacy function. New code should use .compute_psd().plot().
Effective window size : 4.096 (s)
Plotting power spectral density (dB=True).
/home/joshua/.local/lib/python3.10/site-packages/mne/viz/utils.py:158: UserWarning: FigureCanvasAgg is non-interactive, and thus cannot be shown
  (fig or plt).show(**kwargs)
No description has been provided for this image

The plot above (subject 7 task state) shows a decrease in the hump that was at around 8hz to 15dB from 20dB, similar decrease to what subject 6 had. Also compared to background for this subject the amount of power comming from the Frontal lobe (green, cyan, & yellow) seems to be increased from 1hz to 10hz. After 25hz we see an increase in lime and yellow colors way above the other chanels, so Frontal lobe (right dominant) clearly emmiting more power than the other channels.

InΒ [6]:
# Compute PSDs for all raw files
psd_0, freqs_0 = raws[0].compute_psd(fmin=1, fmax=50).get_data(return_freqs=True)
psd_1, freqs_1 = raws[1].compute_psd(fmin=1, fmax=50).get_data(return_freqs=True)
psd_2, freqs_2 = raws[2].compute_psd(fmin=1, fmax=50).get_data(return_freqs=True)
psd_3, freqs_3 = raws[3].compute_psd(fmin=1, fmax=50).get_data(return_freqs=True)

# Average across channels for clearer comparison
psd_0_mean = np.mean(psd_0, axis=0)
psd_1_mean = np.mean(psd_1, axis=0)
psd_2_mean = np.mean(psd_2, axis=0)
psd_3_mean = np.mean(psd_3, axis=0)

# Average the background means to find average background channel signal
psd_background_mean = (psd_0_mean + psd_2_mean) / 2
# Average the task means to find average task channel signal
psd_task_mean = (psd_1_mean + psd_3_mean) / 2

plt.figure(figsize=(10, 6)) # change figure size to be clearly visible

# Plot the average channel signals (the commented out code os for the average signal for a single raw file)

# plt.plot(freqs_0, 10 * np.log10(psd_0_mean), color='cyan', label='Background (Subject 6)')
# plt.plot(freqs_1, 10 * np.log10(psd_1_mean), color='blue', label='Task (Subject 6)')
# plt.plot(freqs_1, 10 * np.log10(psd_2_mean), color='magenta', label='Background (Subject 7)')
# plt.plot(freqs_1, 10 * np.log10(psd_3_mean), color='purple', label='Task (Subject 7)')

plt.plot(freqs_1, 10 * np.log10(psd_background_mean), color='black', label='Mean Background') # plot mean background signal
plt.plot(freqs_1, 10 * np.log10(psd_task_mean), color='red', label='Mean Task') # plot mean task signal
plt.xlabel('Frequency (Hz)') # add clear x-label
plt.ylabel('Power Spectral Density (dB/Hz)') # add clear y-label
plt.title('Power Spectral Density Comparison (Background vs Task)') # add clear title
plt.legend() # show legend to see which line is what
plt.grid(True) # add gridlines for easier comparisions
plt.show() # display plot
Effective window size : 4.096 (s)
Effective window size : 4.096 (s)
Effective window size : 4.096 (s)
Effective window size : 4.096 (s)
No description has been provided for this image

This last plot is to clearly show the difference between the mean background and mean tasks recorded from all channels from both patients. From what we have discussed before, we can validate that it seems that higher frequencies (associated with cognitive demanding tasks) need more power for completing the tasks in comparison to the background.

Overall Thoughts and ConclusionsΒΆ

Lastly I want to mention that subject 6 was an 18 year old male with 4.35 (SD) number of subtractions while subject 7 was a 18 year old female with 13.38 (SD) number of subtractions. From this we can tell that subject 7 did better on the tasks and from what we can tell from these two subjects and the plots is that subject 7 had more drastic amplitude changes than subject 6. Also subject 7 had more of the right frontal lobe active vs subject 6's left frontal lobe. Also the activation of subject 7's right frontal lobe was way more drastic in the higher frequencies vs subject 6's left frontal lobe activation. I think the main difference here is that subject 7 was more comfortable in doing math and therefore was easier to compute the problems in there frontal lobe in comparison to subject 6 which had to rely on other parts of the brain, potentially feeling more emotions (like panicing about being confused about some of the problems), because they were not as familiar with doing those types of math computations.

Q2)ΒΆ

Plot the spectrogram for the two conditions (background and task). Discuss the main differences between the two groups.ΒΆ

There are 21 channels of which there are 4 different files to observe. So what I am going to do is pick 5 channels from different sections of the brain near the center (Fp1, Fz, Cz, Pz, & O1) to analyze given the 4 different files (subject 6 background, subject 6 task, subject 7 background, subject 7 task). This will reduce the number of plots analyzed from 84 to 20 without lossing to much insight.

InΒ [7]:
def plot_spectrogram(raws, channel_name):
    fig, axs = plt.subplots(2, 2, figsize=(12, 10)) # create subplot for easier viewing
    # Loop through the various raw files and a nested loop for easier subploting
    for r in range(2):
        for c in range(2):
            raw = raws[2*r+c] # get the correct raw file
            raw_copy = raw.copy() # avoid deletion of other channels through copying raw
            raw_copy.pick_channels([channel_name]) # pick the given channel
            eeg_data = raw_copy.get_data()[0]  # Shape is (n_channels, n_times)
            sfreq = raw_copy.info['sfreq']  # Sampling frequency

            # Compute spectrogram for the first channel (e.g., Fz)
            f, t, Sxx = sp.signal.spectrogram(eeg_data, fs=sfreq, window=('hann'),
                                            nperseg=1500, noverlap=1000, scaling='density', mode='psd')

            # Plot the spectrogram
            pcm = axs[r, c].pcolormesh(t, f, 10*np.log10(Sxx*1e6**2), cmap='viridis')
            axs[r, c].set_ylabel('Frequency [Hz]') # add clear y-label
            axs[r, c].set_xlabel('Time [sec]') # add clear x-label

            # Choose the title based on the given raw files content
            title = ''
            if 2*r+c == 0:
                title = 'Subject 6 Background'
            if 2*r+c == 1:
                title = 'Subject 6 Task'
            if 2*r+c == 2:
                title = 'Subject 7 Background'
            if 2*r+c == 3:
                title = 'Subject 7 Task'

            axs[r, c].set_title(f'{title} Channel {channel_name}') # title the plot
            plt.colorbar(pcm).set_label('Intensity [dB]') # add clear label to the colorbar

        
    plt.tight_layout() # add correct distancing between subplots
    plt.show() # show plot

plot_spectrogram(raws, 'Fp1') # Plot the Spectrogram for all raw files in the channel Fp1
NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
No description has been provided for this image

This plot shows channel Fp1 over all the raw files and we can clearly see that Subject 7 background has the most intensity in the lower frequencies out of all the other plots. Also the streaks of high intensity are prominent in subject 7 background over long stretches at around 15hz or so in comparision to the other subplots.

However, something which is also interesting here is that when we compare the 2 task subplots, we can see that subject 6 has more activation in the bottom most frequencies (around 1hz). But subject 7 has more activation distributed between that 1hz-8hz region. Overall though, I would say that subject 6 has more intesity throughout the task in comparision to subject 7.

InΒ [25]:
plot_spectrogram(raws, 'Fz') # Plot the Spectrogram for all raw files in the channel Fz
NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
No description has been provided for this image

The plot shows channel Fz and we can see that subject 6's intensity in this region is immense in comparison to subject 7. Even in the background plot there is alot of intensity showing from this channel, but when comparing both of their task subplots, this trend still continues. Even though the intensity colorbar for subject 6 task doesn't cap at 20, we could assume it's near 20 and overall the subplot there is just way brighter that subject 7 task.

InΒ [9]:
plot_spectrogram(raws, 'Cz') # Plot the Spectrogram for all raw files in the channel Cz
NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
No description has been provided for this image

The plot is of channel Cz and the backgrounds are very similar to the previous backgrounds for the other channels. However the Task channel is different in the fact that now there is more intensity going on at this channel for subject 7 in all frequency ranges in comparision to subject 6.

InΒ [10]:
plot_spectrogram(raws, 'Pz') # Plot the Spectrogram for all raw files in the channel Pz
NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
No description has been provided for this image

The plot is on over channel Pz and background is mostly the same as before, the main difference being that there is a clear intensity streak (lasts for many seconds) at around 12hz for both subject 6 and subject 7. Looking at the task subpots, subject 7 has an increased activity from around 1-12hz or so and subject 6 has the higher intesity in the upper frequency ranges.

InΒ [11]:
plot_spectrogram(raws, 'O1') # Plot the Spectrogram for all raw files in the channel O1
NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
No description has been provided for this image

The plot is over the O1 channel and the background is similar to the Pz background plots there. A clear thing which stuck out to me however was a bright streak in intesity through all frequency ranges at 10 seconds on subject 7 task. I don't know if subject 7 saw something crazy (sight because this is the occipital lobe), but the event definitly stands as an outlier here. For the task subplots though, I think that subject 6 was brighter on average in comparision to subject 7 outside of that event near 10 seconds.

Overall Thoughts and ConclusionsΒΆ

During the task portion of the study it seems like subject 7 had more intense lower frequencys on averge in all regions of the brain in comparision to subject 6, however subject 6 had alot of intense activation for higher frequencies in most parts of the brain except for channel Cz, where subject 7 had overall more intensity there. Channel Cz is near the Motor Cortex and that section of the brain is responsible for motor functions. We could therefore conclude baised on this along with the information from the subject info that subject 7 was more confortable with the material, hence a lower intesity of high frequencies in comparision to subject 6. Also that subject 7 was mostly focused on writing the answers down in comparision to subject 6 who seemed to be more focused on thinking through the math problems (because subject 6 was probably not as comfortable with math like subject 7).

Q3)ΒΆ

Plot the time domain signal in Alpha band (8-12 Hz) for the two conditions (background and task). Discuss the main differences between the two groups.ΒΆ

There are 21 channels of which there are 4 different files to observe. So what I am going to do is pick 5 channels from different sections of the brain near the center (Fp1, Fz, Cz, Pz, & O1) to analyze given the 4 different files (subject 6 background, subject 6 task, subject 7 background, subject 7 task). This will reduce the number of plots analyzed from 84 to 20 without lossing to much insight.

InΒ [26]:
# Let us explore some frequency bands
def alpha_band_plot(raws, channel_name):
    fig, axs = plt.subplots(2, 2, figsize=(12, 10)) # create subplot for easier viewing
    # Loop through the various raw files and a nested loop for easier subploting
    for r in range(2):
        for c in range(2):
            raw = raws[2*r+c] # get the correct raw file
            raw_copy = raw.copy() # avoid deletion of other channels through copying raw
            raw_copy.pick_channels([channel_name]) # pick the given channel
            sfreq = raw_copy.info['sfreq']  # Sampling frequency

            # bandpass filter
            raw_copy.filter(8, 12, l_trans_bandwidth=1, h_trans_bandwidth=1)

            # Create time axis in seconds
            n_samples = raw_copy._data.shape[1]
            time_in_sec = np.arange(n_samples) / sfreq

            eeg_data = raw_copy.get_data()[0]  # Get the data of the picked channel

            # make sure filter params are the same
            axs[r, c].plot(time_in_sec, eeg_data)

            # Choose the title based on the given raw files content
            title = ''
            if 2*r+c == 0:
                title = 'Subject 6 Background'
            if 2*r+c == 1:
                title = 'Subject 6 Task'
            if 2*r+c == 2:
                title = 'Subject 7 Background'
            if 2*r+c == 3:
                title = 'Subject 7 Task'

            axs[r, c].set_ylabel('Amplitude [Β΅V]') # add clear y-label
            axs[r, c].set_xlabel('Time [sec]') # add clear x-label
            axs[r, c].set_title(f'{title}') # add clear title to subplot
    fig.suptitle(f'Channel {channel_name} Alpha Band Plots') # add clear title to plot
    plt.tight_layout() # add correct distancing between subplots
    plt.show() # show plot

alpha_band_plot(raws, 'Fp1') # Plot the Alpha band adjusted intensity for all raw files in the channel Fp1
NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 8 - 12 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 8.00
- Lower transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 7.50 Hz)
- Upper passband edge: 12.00 Hz
- Upper transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 12.50 Hz)
- Filter length: 1651 samples (3.302 s)

NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 8 - 12 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 8.00
- Lower transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 7.50 Hz)
- Upper passband edge: 12.00 Hz
- Upper transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 12.50 Hz)
- Filter length: 1651 samples (3.302 s)

NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 8 - 12 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 8.00
- Lower transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 7.50 Hz)
- Upper passband edge: 12.00 Hz
- Upper transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 12.50 Hz)
- Filter length: 1651 samples (3.302 s)

NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 8 - 12 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 8.00
- Lower transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 7.50 Hz)
- Upper passband edge: 12.00 Hz
- Upper transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 12.50 Hz)
- Filter length: 1651 samples (3.302 s)

No description has been provided for this image

The plot is over channel Fp1 and something we can clearly see here is the amplitude is reaching a high peak in the alpha band range at 1.65uV which is higher than the other subplots here. One thing that seems interesting is the fact that the intensity of the amplitude also seems to drop for subject 7 from background to task in a vary meaningful way. This could be because subject 7 was anxious. Also Subject 7 seems to have higher amplitude in both subplots in comparision to subject 6 which could be an indecator that more connections are being at the alpha band level for subject 7.

InΒ [27]:
alpha_band_plot(raws, 'Fz') # Plot the Alpha band adjusted intensity for all raw files in the channel Fz
NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 8 - 12 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 8.00
- Lower transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 7.50 Hz)
- Upper passband edge: 12.00 Hz
- Upper transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 12.50 Hz)
- Filter length: 1651 samples (3.302 s)

NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 8 - 12 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 8.00
- Lower transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 7.50 Hz)
- Upper passband edge: 12.00 Hz
- Upper transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 12.50 Hz)
- Filter length: 1651 samples (3.302 s)

NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 8 - 12 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 8.00
- Lower transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 7.50 Hz)
- Upper passband edge: 12.00 Hz
- Upper transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 12.50 Hz)
- Filter length: 1651 samples (3.302 s)

NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 8 - 12 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 8.00
- Lower transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 7.50 Hz)
- Upper passband edge: 12.00 Hz
- Upper transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 12.50 Hz)
- Filter length: 1651 samples (3.302 s)

No description has been provided for this image

The plot is over channel Fz and subject 7 again has a large amplitude in both regions in comparision to subject 6 in comparing background to background and task to task. For the background subject 7 has around 40% more intesive spikes at the extreme amplitude levels. For the task however, subject 7 has a 2x more amplitude in the extreme case and even one the normal case has substantially more amplitude in comparision to subject 7. Overall there is more brain activty here for subject 7 on channel Fz in the alpha band range.

InΒ [28]:
alpha_band_plot(raws, 'Cz') # Plot the Alpha band adjusted intensity for all raw files in the channel Cz
NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 8 - 12 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 8.00
- Lower transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 7.50 Hz)
- Upper passband edge: 12.00 Hz
- Upper transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 12.50 Hz)
- Filter length: 1651 samples (3.302 s)

NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 8 - 12 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 8.00
- Lower transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 7.50 Hz)
- Upper passband edge: 12.00 Hz
- Upper transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 12.50 Hz)
- Filter length: 1651 samples (3.302 s)

NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 8 - 12 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 8.00
- Lower transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 7.50 Hz)
- Upper passband edge: 12.00 Hz
- Upper transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 12.50 Hz)
- Filter length: 1651 samples (3.302 s)

NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 8 - 12 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 8.00
- Lower transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 7.50 Hz)
- Upper passband edge: 12.00 Hz
- Upper transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 12.50 Hz)
- Filter length: 1651 samples (3.302 s)

No description has been provided for this image

The plot above is on channel Cz and the trends from Fz are present here. Subject 7 has higher amplitudes in both regions in comparision to subject 6 in comparing background to background and task to task. 2x higher amplitudes present in both comparision on the extreme case and still a substantial different in the normal cases. Seems like subject 7 has more brain activity in the alpha band range on channel Cz.

InΒ [29]:
alpha_band_plot(raws, 'Pz') # Plot the Alpha band adjusted intensity for all raw files in the channel Pz
NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 8 - 12 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 8.00
- Lower transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 7.50 Hz)
- Upper passband edge: 12.00 Hz
- Upper transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 12.50 Hz)
- Filter length: 1651 samples (3.302 s)

NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 8 - 12 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 8.00
- Lower transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 7.50 Hz)
- Upper passband edge: 12.00 Hz
- Upper transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 12.50 Hz)
- Filter length: 1651 samples (3.302 s)

NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 8 - 12 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 8.00
- Lower transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 7.50 Hz)
- Upper passband edge: 12.00 Hz
- Upper transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 12.50 Hz)
- Filter length: 1651 samples (3.302 s)

NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 8 - 12 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 8.00
- Lower transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 7.50 Hz)
- Upper passband edge: 12.00 Hz
- Upper transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 12.50 Hz)
- Filter length: 1651 samples (3.302 s)

No description has been provided for this image

The plot above is on channel Pz and the trends from Fz are present here as well, but even more extreme. Subject 7 has higher amplitudes in both regions in comparision to subject 6 in comparing background to background and task to task. 2x higher amplitudes present in background plots and 4x higher amplitudes in task plots. However there are extreme lows in both cases in subject 7 plots, but the could be a sign that signal are clearly passing here that just are not for subject 6 at least on the alpha band range level. Seems like subject 7 has more brain activity in the alpha band range on channel Cz.

InΒ [30]:
alpha_band_plot(raws, 'O1') # Plot the Alpha band adjusted intensity for all raw files in the channel O1
NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 8 - 12 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 8.00
- Lower transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 7.50 Hz)
- Upper passband edge: 12.00 Hz
- Upper transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 12.50 Hz)
- Filter length: 1651 samples (3.302 s)

NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 8 - 12 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 8.00
- Lower transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 7.50 Hz)
- Upper passband edge: 12.00 Hz
- Upper transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 12.50 Hz)
- Filter length: 1651 samples (3.302 s)

NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 8 - 12 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 8.00
- Lower transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 7.50 Hz)
- Upper passband edge: 12.00 Hz
- Upper transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 12.50 Hz)
- Filter length: 1651 samples (3.302 s)

NOTE: pick_channels() is a legacy function. New code should use inst.pick(...).
Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 8 - 12 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 8.00
- Lower transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 7.50 Hz)
- Upper passband edge: 12.00 Hz
- Upper transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 12.50 Hz)
- Filter length: 1651 samples (3.302 s)

No description has been provided for this image

The plot above is on channel O1 and the trends from Fz are present here. Subject 7 has higher amplitudes in both regions in comparision to subject 6 in comparing background to background and task to task. 1.5x higher amplitudes present in background to background and 3x higher amplitdues present in task to task. There are more intensive spikes on subject 7 plots in comparison to subject 6. Seems like subject 7 has more brain activity in the alpha band range on channel O1.

Overall Thoughts and ConclusionsΒΆ

Subject 7 has more alpha band level activity going throughout all aspects of the brain in comparision to subject 6. During the task, this intensity seems to grow even further with many high spikes going off. This could tell is that depending on the problem, the intensity of the jolt changed to be more or less intense, especially in that given region in the brain where the channel was located. We can conclude that subject 7 was more relaxed in comparision to subject 6 because of the higher amplitude of the alpha band range present (Alpha band being a common range for relaxed and passive attention). This also shows in the subject info because subject 7 did better in solving more math problems and was problably more comfortable with the material and therefore more relaxed in the task.

Q4)ΒΆ

Plot the topomap of average power spectral density in the alpha band (8-12 Hz) for the two conditions (background and task). Discuss the differences between the two conditions.ΒΆ

Ploted 60 topomap plots each differing by 1 second each from 1 to 60 seconds for a given raw file. This is obviously a large number of plots, but we can gloss through them and talk about the main things we see like very high or very low activations at certain time periods.

InΒ [21]:
# Function to help print out topomaps in an orderly manner
def topomap_alpha_band_plot(raw, duration):

    # Filter the raw to have alpha band range
    filtered = raw.copy().filter(8, 12, l_trans_bandwidth=1, h_trans_bandwidth=1)

    # Now create epochs from the filtered raw data (alpha band or 8hz to 12hz range)
    events = mne.make_fixed_length_events(filtered, duration=duration)  # Record the length of events (duration taken)
    epochs = mne.Epochs(filtered, events, tmin=0, tmax=60.0, baseline=None) # Find events from 0 to 60 seconds
    
    # Average the epochs to create an evoked object
    evoked = epochs.average()
    
    # Define time points (from 1 to 60 seconds)
    time_points = np.arange(1, 61)

    # Create a grid of subplots (e.g., 12 rows x 5 columns for 60 time points)
    n_rows = 12
    n_cols = 10

    fig, axs = plt.subplots(n_rows, n_cols, figsize=(15, 20), gridspec_kw={'width_ratios': [6, 1] * (n_cols//2)})

    # Loop through time points and plot topomap in each subplot
    r = 0
    while r < n_rows:
        c = 0
        while c < n_cols:
            # Math conversion of r and c to get indexes of time from 0 to 59
            time = time_points[(n_cols//2)*r+(c//2)]
            # Plot the topomap along with the color bar along the next 2 columns in the given row
            evoked.plot_topomap(times=[time], axes=axs[r, c:c+2], show=False, colorbar=True)
            c+=2
        r+=1

    plt.subplots_adjust(hspace=0.4)  # Add space between rows (hspace)
    plt.show() # show plot


topomap_alpha_band_plot(subject6_background, 180) # Print Results for subject 6 background
Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 8 - 12 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 8.00
- Lower transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 7.50 Hz)
- Upper passband edge: 12.00 Hz
- Upper transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 12.50 Hz)
- Filter length: 1651 samples (3.302 s)

Not setting metadata
1 matching events found
No baseline correction applied
0 projection items activated
[Parallel(n_jobs=1)]: Done  17 tasks      | elapsed:    0.0s
No description has been provided for this image

The plot above is over subject 6 background and the main there here to note is there there is alot blue activation in comparison to the red and that might be because of the interval which we are recording these values (every second could be on the lower half of the signal most of the time). The highest amplitude value found here was 18uV. & the average amplitude value out of these is around 9uV (highend).

InΒ [22]:
topomap_alpha_band_plot(subject6_task, 60) # Print Results for subject 6 task
Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 8 - 12 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 8.00
- Lower transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 7.50 Hz)
- Upper passband edge: 12.00 Hz
- Upper transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 12.50 Hz)
- Filter length: 1651 samples (3.302 s)

Not setting metadata
1 matching events found
No baseline correction applied
0 projection items activated
[Parallel(n_jobs=1)]: Done  17 tasks      | elapsed:    0.0s
No description has been provided for this image

The plot above is over subject 6 task and the highest amplitude present is around 7uV. This is less than half what was the highest amplitude found in the background for subject 6. This tells us that in the alpha band frequency range that the subject is less relaxed and therefore these types of frequencies are not as present. Out of all these plots it seems like the most extreme amplitude areas were located in the back of the head near the occipital lobe, probably because subject 6 was more relaxed by looking at the task in comparison to thinking about the task.

InΒ [23]:
topomap_alpha_band_plot(subject7_background, 180) # Print Results for subject 7 background
Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 8 - 12 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 8.00
- Lower transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 7.50 Hz)
- Upper passband edge: 12.00 Hz
- Upper transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 12.50 Hz)
- Filter length: 1651 samples (3.302 s)

Not setting metadata
1 matching events found
No baseline correction applied
0 projection items activated
[Parallel(n_jobs=1)]: Done  17 tasks      | elapsed:    0.1s
No description has been provided for this image

The plot above is over subject 7 background and the highest amplitude value is around 33uV given 47 seconds. This is almost 2x larger than the largest value found on the subject 6 background topomap plot. Another thing to mention is that the density of the amplitudes seem to be evenly distributed amongst the brain. So for example the topomap at 36 seconds has a bunch of high amplitudes at different sections of the brain, this can be found in the 44 second topomap and others to, the point is that it's more prevalent that this is the case for subject 7 background over subject 6 background.

InΒ [24]:
topomap_alpha_band_plot(subject7_task, 60) # Print Results for subject 7 task
Filtering raw data in 1 contiguous segment
Setting up band-pass filter from 8 - 12 Hz

FIR filter parameters
---------------------
Designing a one-pass, zero-phase, non-causal bandpass filter:
- Windowed time-domain design (firwin) method
- Hamming window with 0.0194 passband ripple and 53 dB stopband attenuation
- Lower passband edge: 8.00
- Lower transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 7.50 Hz)
- Upper passband edge: 12.00 Hz
- Upper transition bandwidth: 1.00 Hz (-6 dB cutoff frequency: 12.50 Hz)
- Filter length: 1651 samples (3.302 s)

Not setting metadata
1 matching events found
No baseline correction applied
0 projection items activated
[Parallel(n_jobs=1)]: Done  17 tasks      | elapsed:    0.0s
No description has been provided for this image

The plot above is over subject 7 task and the highest amplitude found was around 26uV, which is a little less than what we found in the subject 7 background topomap plot. That amplitude is also 4x higher than the highest amplitude found in the subject 6 task topomap plot. It also seems that alot of the dense amplitude changes are happening in the center of the head where the motor cortex is located along with very minimal amplitude happening in the frontal lobe on average.

Overall Thoughts and conclusionsΒΆ

Sense the alpha band has the seen trait of being corralated with relaxation and passive attention. We can tell fron the high amplitudes observed that subject 7 was way more relaxed in comparison to subject 6 because subject 7 had a way higher amplitude in this range. Another interesting thing to mention is that subject 7 didn't have much amplitude near the frontal lobe compared to other parts of the brain, while subject 6 had a higher amplitude in the frontal lobe compared to other parts of the brain. This could mean that Other parts of the brain were more relaxed in subjects 7's case, but the front lobe was interestingly enough the more relaxed region in subject 6's case. However subject 6 could have been panic or thinking in a way which required other regions of the brain to not be as relaxed (other frequence band types). However like previously said, subject 7 was overall way more relaxed than subject 6.